import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { diffTokenTime } from '@/utils/auth.js'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  // 在请求头添加token
  (config) => {
    if (localStorage.getItem('token')) {
      /*  if (diffTokenTime()) {
        store.dispatch('app/logout')
        return Promise.reject(new Error('token失效'))
      } */
      // config.headers.Authorization = localStorage.getItem('token')
      config.headers.token = localStorage.getItem('token')
    }
    NProgress.start()
    return config
  },
  (error) => {
    return Promise.reject(error, message)
  }
)

service.interceptors.response.use(
  (response) => {
    // console.log(response)
    const res = response.data
    if (res.code !== 200) {
      //#region
      // token失效
      /*  if (res.code === 224) {
        ElMessageBox.confirm(
          'You have been logged out, you can cancel to stay on this page, or log in again',
          'Confirm logout',
          {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('app/logout')
        })
      } */
      //#endregion
      // 用户或密码错误 验证码错误或失效 账户正常或禁用
      if (res.code === 207 || res.code === 223 || res.code === 205) {
        ElMessage({
          type: 'error',
          message: res.message,
          duration: 3 * 1000
        })
        return res
      }
      // 在获取数据时发生token失效导致无法获取数据
      /* if (res.code === 555) {
        // 如果在这显示错误信息可能会发生多个请求出错然后弹出多个体验教超
        store.dispatch('app/logout')
      } */
      NProgress.done()
      // res.message对应的是后端返回的信息
      // new Error()相当于创建一个Error对象 里面放了{Error:传入错误的消息}
      return Promise.reject(res.message)
    } else {
      NProgress.done()
      return res
    }
  },
  // 没有响应
  (error) => {
    // console.log(error)
    ElMessage.error(error.message)
    return Promise.reject(new Error(error.message))
  }
)

export default service
